class Tile {
  constructor(opt = {}) {
    this.ctx = opt.ctx
    this.x = opt.x
    this.y = opt.y
    this.row = opt.row
    this.col = opt.col
    this.zoom = opt.zoom
    this.shouldRender = opt.shouldRender
    this.loaded = false
    this.cacheKey = `${this.row}-${this.col}-${this.zoom}`
    this.url = ''
    this.img = ''
    this.createUrl()
    this.load()
  }

  createUrl() {
    const domainIndexList = [1, 2, 3, 4]
    const domainIndex =
      domainIndexList[Math.floor(Math.random() * domainIndexList.length)]
    this.url = `https://webrd0${domainIndex}.is.autonavi.com/appmaptile?x=${this.row}&y=${this.col}&z=${this.zoom}&lang=zh_cn&size=1&scale=1&style=8`
  }

  load() {
    this.img = new Image()
    this.img.src = this.url
    this.img.onload = () => {
      this.loaded = true
      this.render()
    }
  }
  render() {
    if (this.loaded && this.img) {
      this.ctx.drawImage(this.img, this.x, this.y)
      this.ctx.strokeRect(this.x, this.y, 256, 256)
      this.ctx.font="16px 微软雅黑";
      this.ctx.fillText(`${this.row}，${this.col}`,this.x+128,this.y-128)
    }
  }
  updatePos(x, y) {
    this.x = x
    this.y = y
    return this
  }
}

export default Tile